<template>
  <div class="user-profile">
    <!-- 顶部封面 -->
    <div class="cover-wrap">
      <div class="cover-mask">
        <div class="cover-emoji">🖼️</div>
        <div class="cover-title">{{ userInfo.userName }} 的作品集</div>
        <div class="cover-sub">「展示我的精彩作品」</div>
      </div>
    </div>

    <!-- 主体 -->
    <div class="content-wrap">
      <!-- 返回按钮 -->
      <div class="back-button">
        <a-button type="link" @click="$router.push('/')">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回主页
        </a-button>
      </div>

      <a-card class="portfolio-card" :bordered="false">
        <a-tabs v-model:activeKey="activeKey" @change="handleTabChange">
          <a-tab-pane key="1" tab="我的作品">
            <div class="portfolio-content">
              <div class="portfolio-controls">
                <a-select
                  v-model:value="filter.category"
                  style="width: 150px; margin-right: 16px;"
                  placeholder="分类筛选"
                  :options="categoryOptions"
                  allow-clear
                  @change="handleFilterChange"
                  size="small"
                />
                <a-select
                  v-model:value="filter.sortField"
                  style="width: 150px;"
                  placeholder="排序方式"
                  :options="sortOptions"
                  @change="handleFilterChange"
                  size="small"
                />
              </div>

              <!-- 作品网格 -->
              <div class="portfolio-grid">
                <a-empty v-if="pictureList.length === 0" description="暂无作品" />
                <div 
                  class="portfolio-item"
                  v-for="picture in pictureList"
                  :key="picture.id"
                  @click="showPictureDetail(picture)"
                >
                  <a-image 
                    :src="picture.url" 
                    :preview="false"
                    class="portfolio-image"
                    alt="作品图片"
                  />
                  <div class="portfolio-item-info">
                    <h3 class="picture-title">{{ picture.name }}</h3>
                    <div class="picture-meta">
                      <span>{{ formatDate(picture.createTime) }}</span>
                      <span v-if="picture.category">{{ picture.category }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 分页 -->
              <div class="pagination-container" v-if="pictureList.length > 0">
                <a-pagination
                  v-model:current="pagination.current"
                  v-model:page-size="pagination.pageSize"
                  :total="pagination.total"
                  show-size-changer
                  @change="handlePageChange"
                />
              </div>
            </div>
          </a-tab-pane>

          <a-tab-pane key="2" tab="我的收藏">
            <div class="portfolio-content">
              <div class="portfolio-controls">
                <a-select
                  v-model:value="favoriteFilter.category"
                  style="width: 150px; margin-right: 16px;"
                  placeholder="分类筛选"
                  :options="categoryOptions"
                  allow-clear
                  @change="handleFavoriteFilterChange"
                  size="small"
                />
                <a-select
                  v-model:value="favoriteFilter.sortField"
                  style="width: 150px;"
                  placeholder="排序方式"
                  :options="sortOptions"
                  @change="handleFavoriteFilterChange"
                  size="small"
                />
              </div>

              <!-- 收藏网格 -->
              <div class="portfolio-grid">
                <a-empty v-if="favoriteList.length === 0" description="暂无收藏" />
                <div 
                  class="portfolio-item"
                  v-for="picture in favoriteList"
                  :key="picture.id"
                  @click="showPictureDetail(picture)"
                >
                  <a-image 
                    :src="picture.url" 
                    :preview="false"
                    class="portfolio-image"
                    alt="收藏图片"
                  />
                  <div class="portfolio-item-info">
                    <h3 class="picture-title">{{ picture.name }}</h3>
                    <div class="picture-meta">
                      <span>{{ formatDate(picture.createTime) }}</span>
                      <span v-if="picture.category">{{ picture.category }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 分页 -->
              <div class="pagination-container" v-if="favoriteList.length > 0">
                <a-pagination
                  v-model:current="favoritePagination.current"
                  v-model:page-size="favoritePagination.pageSize"
                  :total="favoritePagination.total"
                  show-size-changer
                  @change="handleFavoritePageChange"
                />
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>

    <!-- 图片详情模态框 -->
    <a-modal
      v-model:open="detailVisible"
      :footer="null"
      width="80%"
      wrap-class-name="portfolio-detail-modal"
      @cancel="detailVisible = false"
    >
      <template #title>
        <div class="detail-header">
          <h2>{{ currentPicture?.name }}</h2>
        </div>
      </template>
      <div class="detail-content" v-if="currentPicture">
        <div class="detail-image-container">
          <img :src="currentPicture.url" :alt="currentPicture.name" class="detail-image" />
        </div>
        <div class="detail-info">
          <a-descriptions :column="1" size="small">
            <a-descriptions-item label="图片名称">{{ currentPicture.name }}</a-descriptions-item>
            <a-descriptions-item label="简介">{{ currentPicture.introduction || '-' }}</a-descriptions-item>
            <a-descriptions-item label="分类">{{ currentPicture.category || '-' }}</a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="tag in currentPicture.tags" :key="tag">{{ tag }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="尺寸">
              {{ currentPicture.picWidth }} × {{ currentPicture.picHeight }}
            </a-descriptions-item>
            <a-descriptions-item label="大小">
              {{ formatFileSize(currentPicture.picSize) }}
            </a-descriptions-item>
            <a-descriptions-item label="格式">{{ currentPicture.picFormat }}</a-descriptions-item>
            <a-descriptions-item label="创建时间">{{ formatDate(currentPicture.createTime) }}</a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { getLoginUserUsingGet } from '@/api/userController'
import { listPictureVoByPageUsingPost } from '@/api/pictureController'
import { listCategoryUsingPost } from '@/api/pictureCategoryController'

const activeKey = ref('1')
const userInfo = ref<any>({})
const pictureList = ref<any[]>([])
const favoriteList = ref<any[]>([])
const detailVisible = ref(false)
const currentPicture = ref<any>(null)

// 分页参数 - 我的作品
const pagination = ref({
  current: 1,
  pageSize: 12,
  total: 0
})

// 分页参数 - 我的收藏
const favoritePagination = ref({
  current: 1,
  pageSize: 12,
  total: 0
})

// 筛选和排序 - 我的作品
const filter = reactive({
  category: undefined,
  sortField: 'createTime_desc',
  sortOrder: 'desc'
})

// 筛选和排序 - 我的收藏
const favoriteFilter = reactive({
  category: undefined,
  sortField: 'createTime_desc',
  sortOrder: 'desc'
})

// 分类选项
const categoryOptions = ref<{ label: string; value: string }[]>([])
const sortOptions = [
  { label: '最新上传', value: 'createTime_desc' },
  { label: '最早上传', value: 'createTime_asc' },
  { label: '名称排序 (A-Z)', value: 'name_asc' },
  { label: '名称排序 (Z-A)', value: 'name_desc' }
]

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getLoginUserUsingGet()
    if (res.data.code === 0) {
      userInfo.value = res.data.data || {}
      // 获取用户图片列表
      await fetchUserPictures()
    } else {
      message.error(res.data.message || '获取用户信息失败')
    }
  } catch (error) {
    message.error('获取用户信息失败')
  }
}

// 获取用户图片列表
const fetchUserPictures = async () => {
  try {
    const params: any = {
      userId: userInfo.value.id,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize
    }

    // 添加筛选条件
    if (filter.category) {
      params.category = filter.category
    }

    // 添加排序条件
    if (filter.sortField) {
      if (filter.sortField.endsWith('_asc')) {
        params.sortField = filter.sortField.replace('_asc', '')
        params.sortOrder = 'asc'
      } else if (filter.sortField.endsWith('_desc')) {
        params.sortField = filter.sortField.replace('_desc', '')
        params.sortOrder = 'desc'
      } else {
        // 兼容旧的值
        if (filter.sortField === 'createTime') {
          params.sortField = 'createTime'
          params.sortOrder = 'desc'
        } else {
          params.sortField = filter.sortField
          params.sortOrder = 'desc' // 默认降序
        }
      }
    }

    const res = await listPictureVoByPageUsingPost(params)
    if (res.data.code === 0) {
      pictureList.value = res.data.data?.records || []
      pagination.value.total = res.data.data?.total || 0
    } else {
      message.error(res.data.message || '获取图片列表失败')
    }
  } catch (error) {
    message.error('获取图片列表失败')
  }
}

// 获取用户收藏列表（暂时用模拟数据）
const fetchUserFavorites = async () => {
  try {
    // 这里需要调用获取用户收藏图片的API
    // 暂时用模拟数据
    favoriteList.value = []
    favoritePagination.value.total = 0
    
    // 如果有实际的API，这里应该像fetchUserPictures一样处理
    /*
    const params: any = {
      userId: userInfo.value.id,
      favourUserId: userInfo.value.id, // 收藏用户ID，表示查询该用户收藏的图片
      current: favoritePagination.value.current,
      pageSize: favoritePagination.value.pageSize
    }

    // 添加筛选条件
    if (favoriteFilter.category) {
      params.category = favoriteFilter.category
    }

    // 添加排序条件
    if (favoriteFilter.sortField) {
      if (favoriteFilter.sortField.endsWith('_asc')) {
        params.sortField = favoriteFilter.sortField.replace('_asc', '')
        params.sortOrder = 'asc'
      } else if (favoriteFilter.sortField.endsWith('_desc')) {
        params.sortField = favoriteFilter.sortField.replace('_desc', '')
        params.sortOrder = 'desc'
      } else {
        // 兼容旧的值
        if (favoriteFilter.sortField === 'createTime') {
          params.sortField = 'createTime'
          params.sortOrder = 'desc'
        } else {
          params.sortField = favoriteFilter.sortField
          params.sortOrder = 'desc' // 默认降序
        }
      }
    }

    const res = await listPictureVoByPageUsingPost(params)
    if (res.data.code === 0) {
      favoriteList.value = res.data.data?.records || []
      favoritePagination.value.total = res.data.data?.total || 0
    } else {
      message.error(res.data.message || '获取收藏列表失败')
    }
    */
  } catch (error) {
    message.error('获取收藏列表失败')
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await listCategoryUsingPost({})
    if (res.data.code === 0) {
      categoryOptions.value = (res.data.data || []).map((item: any) => ({
        label: item.categoryName,
        value: item.categoryName
      }))
      // 在开头添加"全部"选项
      categoryOptions.value.unshift({ label: '全部分类', value: '' })
    } else {
      message.error(res.data.message || '获取分类列表失败')
    }
  } catch (error) {
    message.error('获取分类列表失败')
  }
}

// 处理标签页切换
const handleTabChange = (key: string) => {
  if (key === '1') {
    fetchUserPictures()
  } else if (key === '2') {
    fetchUserFavorites()
  }
}

// 处理筛选变化 - 我的作品
const handleFilterChange = () => {
  pagination.value.current = 1
  fetchUserPictures()
}

// 处理筛选变化 - 我的收藏
const handleFavoriteFilterChange = () => {
  favoritePagination.value.current = 1
  fetchUserFavorites() // 实际应用中这里应该调用真实的API
  // 模拟更新收藏列表
  fetchUserPictures() // 临时复用作品获取函数作为演示
}

// 处理分页变化 - 我的作品
const handlePageChange = (page: number, pageSize?: number) => {
  pagination.value.current = page
  if (pageSize) {
    pagination.value.pageSize = pageSize
  }
  fetchUserPictures()
}

// 处理分页变化 - 我的收藏
const handleFavoritePageChange = (page: number, pageSize?: number) => {
  favoritePagination.value.current = page
  if (pageSize) {
    favoritePagination.value.pageSize = pageSize
  }
  fetchUserFavorites()
}

// 显示图片详情
const showPictureDetail = (picture: any) => {
  currentPicture.value = picture
  detailVisible.value = true
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '-'
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  }
}

onMounted(() => {
  fetchUserInfo()
  fetchCategories()
})
</script>

<style scoped>
.user-profile {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
}

.cover-wrap {
  height: 220px;
  background: url('https://images.unsplash.com/photo-1506318137071-a8e063b4bec0?auto=format&fit=crop&w=1650&q=80')
    center/cover no-repeat;
  position: relative;
}

.cover-mask {
  position: absolute;
  inset: 0;
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(12px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #2c3e50;
}

.cover-emoji {
  font-size: 48px;
  margin-bottom: 8px;
}

.cover-title {
  font-size: 32px;
  font-weight: 600;
  letter-spacing: 2px;
}

.cover-sub {
  font-size: 14px;
  margin-top: 4px;
  opacity: 0.8;
}

.content-wrap {
  max-width: 1200px;
  margin: -40px auto 0;
  padding: 0 24px 40px;
  position: relative;
  z-index: 2;
}

.back-button {
  margin-bottom: 20px;
}

.portfolio-card {
  border-radius: 20px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
  padding: 24px;
}

/* 作品集控制区域 */
.portfolio-controls {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

/* 作品网格 */
.portfolio-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.portfolio-item {
  background: #fafafa;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
}

.portfolio-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.portfolio-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  display: block;
}

.portfolio-item-info {
  padding: 12px;
}

.picture-title {
  font-size: 15px;
  font-weight: 600;
  margin: 0 0 6px 0;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.picture-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

/* 详情模态框 */
.portfolio-detail-modal :deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

.detail-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.detail-content {
  display: flex;
  gap: 30px;
  max-height: 70vh;
  overflow-y: auto;
}

.detail-image-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 8px;
  min-height: 400px;
}

.detail-image {
  max-width: 100%;
  max-height: 60vh;
  object-fit: contain;
}

.detail-info {
  flex: 1;
  min-width: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .portfolio-controls {
    justify-content: center;
  }
  
  .detail-content {
    flex-direction: column;
  }
  
  .detail-image-container {
    min-height: 250px;
  }
}
</style>